package com.jin.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jin.Exception.http.ServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.AttributeConverter;
import javax.persistence.Convert;
import javax.persistence.Converter;
import java.text.AttributedCharacterIterator;
import java.util.HashMap;
import java.util.Map;

//这个类处理map和json的双向转换，实现AttributeConverter接口让jpa自动调用这个类完成序列化和反序列化
//需要传入两个泛型：1.当前要转换字段的类型 2.数据库中对应的java中的类型 实际上就是双向的转换
@Converter
public class MapAndJson implements AttributeConverter<Map<String,Object>,String> {
    //序列化的对象
    @Autowired
    private ObjectMapper mapper;
    //序列化
    @Override
    public String convertToDatabaseColumn(Map<String, Object> map) {
        try {
            return mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
        
    }

    //反序列化
    @Override
    public Map<String, Object> convertToEntityAttribute(String s) {
        //第二个参数是你当前需要反序列化的属性的元类
        try {
            return mapper.readValue(s, HashMap.class);
        } catch (JsonProcessingException e) {
            throw new ServerErrorException(9999);
        }
    }
}
